import sys
import random

from ai.enemy import Enemy
from shared.entities import Player

sys.path.insert(0, '..')

from maze import mazemaker


class GameState:
    def __init__(self, maze=None, enemies=10):
        if maze is None:
            maze = mazemaker.DepthFirstGenerator(5, 5)
        self.maze = maze
        self.player = Player((1, 1), self)
        self.enemies = []
        for i in range(enemies):
            location = (random.randint(2, self.maze.sizeX - 1), random.randint(2, self.maze.sizeY - 1))
            while (self.maze.get(*location) != 1):
                location = (random.randint(2, self.maze.sizeX - 1), random.randint(2, self.maze.sizeY - 1))

            self.enemies.append(Enemy(location, self, random.randint(1, 3)))
        self.condition = "running"

    def entities(self):
        """Yield all significant entities (players and enemies)."""
        yield self.player
        for enemy in self.enemies:
            yield enemy

    def do_moves(self):
        """Move all entities in this state based off their facings."""
        for ent in self.entities():
            ent.do_move()

    def checkWinLoss(self):
        if self.player.location in self.maze.exits:
            self.condition = "won"
        for enemy in self.enemies:
            if enemy.location == self.player.location:
                self.condition = "lost"

    def __str__(self):
        """Return a string representation of this GameState."""

        lines = [
            str(self.maze)
            ]
        for ent in self.entities():
            lines.append("{} at {}".format(
                type(ent).__name__, ent.location
                ))
        return "\n".join(lines)


if __name__ == "__main__":
    gs = GameState()
    print(gs)
